import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hao/page/launch/LaunchViewModel.dart';
import 'package:hao/utils/Utils.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_picker/Picker.dart';

class SetViewModel extends GetxController {
  final version = "".obs;
  int type = 0;
  final dayTypes = ["跟随系统", "关闭", "开启"];
  final model = "".obs;

  void loadVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    version.value = packageInfo.version;

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    type = sharedPreferences.getInt("mode") ?? 0;

    model.value = dayTypes[type];
  }

  @override
  void onInit() {
    super.onInit();

    loadVersion();
  }

  void logout() {
    showAlert("提示", "确定要退出登录？", () async {
      Get.back();
      SharedPreferences preferences = await SharedPreferences.getInstance();
      preferences.setBool("hasLogin", false);

      LaunchViewModel _viewModel = Get.find();
      _viewModel.changeLoginState();
    });
  }

  void changeMode() {
    Picker(
            height: 200,
            itemExtent: 50,
            confirmText: "确定",
            cancelText: "取消",
            backgroundColor: Get.theme.primaryColor,
            onConfirm: (Picker picker, List value) async {
              int index = value.first;
              if (type == index) {
                return;
              }
              type = index;

              SharedPreferences sharedPreferences =
                  await SharedPreferences.getInstance();
              sharedPreferences.setInt("mode", index);

              await configMode();
              model.value = dayTypes[index];
            },
            adapter: PickerDataAdapter(
                data: dayTypes
                    .map(
                      (e) => PickerItem(
                          text: Container(
                        alignment: Alignment.center,
                        child: Text(
                          e.toString(),
                          style: TextStyle(color: Get.theme.primaryColorDark),
                        ),
                      )),
                    )
                    .toList()))
        .showModal(Get.context!);
  }
}
